from sqlalchemy import PrimaryKeyConstraint, Sequence, text
from sqlalchemy.dialects.postgresql import TIMESTAMP

from tzq.extensions import db


class Permission(db.Model):
    """ 权限表 """
    __tablename__ = 'dm_permission_t'
    __table_args__ = (
        # 主键约束
        PrimaryKeyConstraint('permission_id', name='dm_permission_pk', comment='主键约束'),
        # 表注释
        {'comment': '权限表'},
    )
    permission_id = db.Column(
        db.BigInteger,
        Sequence('dm_permission_s'),
        primary_key=True,
        server_default=Sequence('dm_permission_s').next_value(),
        nullable=False,  # 非空约束。False为禁止为空
        comment='主键ID'
    )
    ip = db.Column(db.String(50), nullable=False, comment='IP地址')
    user_code = db.Column(
        db.String(300),
        Sequence('dm_permission_user_code_s', 1001),
        # server_default="DM" + str(Sequence('dm_permission_user_code_s').next_value()),
        server_default=text("concat('DM', nextval('dm_permission_user_code_s'))"),
        nullable=False,
        comment='用户编码：从DM1001开始'
    )
    user_name = db.Column(db.String(300), nullable=False, comment='用户名')
    user_type = db.Column(db.String(50), nullable=False,
                          comment='用户类型：管理员(所有权限)，读写用户(读、写、导出权限)，读用户(读、导出、权限)')
    comment = db.Column(db.String(3000), comment='备注')
    delete_flag = db.Column(db.String(10), nullable=False, server_default='N',
                            comment='删除标识：记录该记录是否删除，Y=>删除、N=>未删除')
    created_by = db.Column(db.String(50), nullable=False, server_default='0.0.0.0',
                           comment='创建人：创建人的客户端IP地址')
    creation_date = db.Column(TIMESTAMP(timezone=False, precision=0), nullable=False,
                              server_default=db.func.clock_timestamp(), comment='创建时间')
    last_updated_by = db.Column(db.String(50), nullable=False, server_default='0.0.0.0',
                                comment='最后更新人：更新人的客户端IP地址')
    last_update_date = db.Column(TIMESTAMP(timezone=False, precision=0), nullable=False,
                                 server_default=db.func.clock_timestamp(), comment='最后更新时间')

    def to_dict(self):
        return {
            'permission_id': self.permission_id,
            'ip': self.ip,
            'user_code': self.user_code,
            'user_name': self.user_name,
            'user_type': self.user_type,
            'comment': self.comment,
            'delete_flag': self.delete_flag,
            'created_by': self.created_by,
            'creation_date': self.creation_date.strftime('%Y-%m-%d %H:%M:%S'),
            'last_updated_by': self.last_updated_by,
            'last_update_date': self.last_update_date.strftime('%Y-%m-%d %H:%M:%S'),
        }
